package io.renren.modules.device.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import io.renren.common.utils.ShiroUtils;
import io.renren.modules.app.entity.UserEntity;
import io.renren.modules.app.service.UserService;
import io.renren.modules.device.service.DeviceDataService;
import io.renren.modules.sys.dao.SysUserDao;
import io.renren.modules.sys.entity.SysDictDetailEntity;
import io.renren.modules.sys.entity.SysDictEntity;
import io.renren.modules.sys.entity.SysUserEntity;
import io.renren.modules.sys.service.SysDictDetailService;
import io.renren.modules.sys.service.SysDictService;
import io.renren.modules.sys.service.SysRoleService;
import io.renren.modules.sys.service.SysUserService;
import io.renren.modules.sys.service.impl.SysDictDetailServiceImpl;
import io.renren.modules.zjwl.dao.SimCardDao;
import io.renren.modules.zjwl.service.SimCardService;
import org.apache.commons.lang.ObjectUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.Query;

import io.renren.modules.device.dao.DeviceDao;
import io.renren.modules.device.entity.DeviceEntity;
import io.renren.modules.device.service.DeviceService;


@Service("deviceService")
public class DeviceServiceImpl extends ServiceImpl<DeviceDao, DeviceEntity> implements DeviceService {

    @Autowired
    private DeviceDataService deviceDataService;
    @Autowired
    private UserService userService;

    @Autowired
    private SysDictDetailService sysDictDetailService;
    @Autowired
    private SysDictService sysDictService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SimCardDao simCardDao;
    private Map<String, BigDecimal> deviceOnlineMap = new HashMap<>();

    @Override
    public boolean checkDeviceBind(String lotDeviceId) {
        QueryWrapper<DeviceEntity> deviceEntityQueryWrapper = new QueryWrapper<>();
        deviceEntityQueryWrapper.eq("lot_device_id", lotDeviceId);
        List<DeviceEntity> deviceEntities = list(deviceEntityQueryWrapper);
        if(CollectionUtil.isNotEmpty(deviceEntities)){
            return true;
        }
        return false;
    }


    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        getDeviceType();
        QueryWrapper<DeviceEntity> queryWrapper = new QueryWrapper<>();
        if (!params.containsKey("all")) {
            queryWrapper.eq("user_id", params.get("userId"));
        }
        queryWrapper.orderByAsc("id");
        IPage<DeviceEntity> page = this.page(
                new Query<DeviceEntity>().getPage(params),
                queryWrapper
        );
        List<DeviceEntity> deviceEntities = page.getRecords();
        deviceEntities.forEach(deviceEntity -> {
            int secondCount = 60 * 30;
            if (deviceOnlineMap.containsKey(deviceEntity.getDeviceType())) {
                secondCount = deviceOnlineMap.get(deviceEntity.getDeviceType()).multiply(new BigDecimal(3600))
                        .setScale(2, BigDecimal.ROUND_UP).intValue();
            }
            int count = deviceDataService.deviceOffline(secondCount, deviceEntity.getLotDeviceId());
            if (count <= 0) {
                deviceEntity.setOnline(false);
            }
        });
        return new PageUtils(page);
    }

    public static void main(String[] args) {
        BigDecimal bigDecimal = new BigDecimal(0.03);
        System.out.println(bigDecimal.multiply(new BigDecimal(60)).setScale(2, BigDecimal.ROUND_UP).floatValue());
    }

    private void getDeviceType() {
        QueryWrapper<SysDictEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name", "deviceType");
        List<SysDictEntity> sysDictEntities = sysDictService.list(queryWrapper);
        if (CollectionUtil.isNotEmpty(sysDictEntities)) {
            SysDictEntity sysDictEntity = sysDictEntities.get(0);
            QueryWrapper<SysDictDetailEntity> sysDictEntityQueryWrapper = new QueryWrapper<>();
            sysDictEntityQueryWrapper.eq("dict_id", sysDictEntity.getDictId());
            List<SysDictDetailEntity> sysDictDetailEntities = sysDictDetailService.list(sysDictEntityQueryWrapper);
            sysDictDetailEntities.forEach(sysDictDetailEntity -> {
                deviceOnlineMap.put(sysDictDetailEntity.getValue(), sysDictDetailEntity.getThreshold());
            });
        }
    }

    @Override
    public PageUtils queryPageAdmin(Map<String, Object> params) {
        getDeviceType();

        QueryWrapper<DeviceEntity> queryWrapper = new QueryWrapper<>();

        if (params.containsKey("lotDeviceId") && StringUtils.isNotEmpty((String) params.get("lotDeviceId"))) {
            queryWrapper.like("lot_device_id", params.get("lotDeviceId"));
        }
        if (params.containsKey("userId") && Integer.parseInt(params.get("userId").toString()) > 0) {
            queryWrapper.eq("user_id", params.get("userId"));
        }
        if (params.containsKey("deviceName") && StringUtils.isNotEmpty((String) params.get("deviceName"))) {
            queryWrapper.like("name", params.get("deviceName"));
        }
        if (params.containsKey("address") && StringUtils.isNotEmpty((String) params.get("address"))) {
//            queryWrapper.or().like("province", params.get("address")).
//                    or().like("city", params.get("address")).
//                    or().like("area", params.get("address"));
            queryWrapper.like("address", params.get("address"));
        }
        //todo 如果当前用户是代理商角色
        if (isAgent()) {
            List<String> deviceIdStrList = simCardDao.findDeviceIdByAgentId(ShiroUtils.getUserEntity().getAgentId());
            queryWrapper.in("lot_device_id", deviceIdStrList);
        }
        queryWrapper.orderByDesc("id");

        IPage<DeviceEntity> page = this.page(
                new Query<DeviceEntity>().getPage(params),
                queryWrapper
        );
        List<DeviceEntity> deviceEntities = page.getRecords();
        deviceEntities.forEach(deviceEntity -> {
            int secondCount = 60 * 30;
            if (deviceOnlineMap.containsKey(deviceEntity.getDeviceType())) {
                secondCount = deviceOnlineMap.get(deviceEntity.getDeviceType()).multiply(new BigDecimal(3600))
                        .setScale(2, BigDecimal.ROUND_UP).intValue();
            }
            int count = deviceDataService.deviceOffline(secondCount, deviceEntity.getLotDeviceId());
            if (count <= 0) {
                deviceEntity.setOnline(false);
            }
            UserEntity userEntity = userService.getById(deviceEntity.getUserId());
            if (ObjectUtil.isNotNull(userEntity)) {
                deviceEntity.setUserName(userEntity.getUsername());
            }
        });
        deviceEntities.forEach(deviceEntity -> {

        });
        return new PageUtils(page);
    }

    public boolean isAgent() {
        SysUserEntity userEntity = ShiroUtils.getUserEntity();
        if (userEntity.getAgentId() != 0) {
            return true;
        }
        return false;
    }

}